package cn.iocoder.yudao.framework.operatelog.core.Logger;

import cn.iocoder.yudao.framework.operatelog.api.dal.mysql.permission.logObjectMapper;
import cn.iocoder.yudao.framework.operatelog.api.tools.SpringUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import lombok.var;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auth zh 2021/11/16 14:02
 */
@Component
public class Logger implements LoggerInterface {
    private final ApplicationContext applicationContext = SpringUtils.getApplicationContext();
    private static Logger log = null;


    private Logger() {
    }

    synchronized public static Logger getLog() {
        if (log == null) {
            log = new Logger();
        }
        return log;
    }


    private void log(Class c) {
    }

    static void logInFile(Class c) {
        getLog().log(c);
    }

    @Override
    public void LoggerInfile(Class c) {
        logInFile(c);
    }

    @Override
    public void LoggerInfile(String MethodName) {
        logInFile(MethodName);
    }

    static void logInFile(String methodName) {
        getLog().log(methodName);
    }

    private void log(String MethodName) {
        try {
            if (MethodName != null) {
                String packageName = "";
                String ClassName = MethodName;
                Date logDate = new Date();
                var sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                LoginUser curUser = SecurityFrameworkUtils.getLoginUser();
                if (curUser != null) {
                    String userId = String.valueOf(SecurityFrameworkUtils.getLoginUser().getId());
                    logObject logObject = new logObject(sdf.format(logDate), InetAddress.getLocalHost().toString(), packageName, ClassName, userId);
                    logObjectMapper logObjectMapper = applicationContext.getBean(logObjectMapper.class);
                    logObjectMapper.insertLogger(logObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("错误信息" + e.getMessage());
        }
    }
}
